/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import hibernate.HibernateUtil;
import hibernate.dao.Login;
import hibernate.dao.Registrologin;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;

/**
 *
 * @author 0040481121043
 */
public class LoginController {
    
    private final static int LIMIT = 4;
    
    private LoginListener mLoginListener = null;
    private int errors = 0;       
    
    public LoginController() {
        this(null);
    }
    
    public LoginController(LoginListener pLoginListener) {
        mLoginListener = pLoginListener;
    }
        
    public void checkUser(String pName, String pPassword) {
        if (errors >= LIMIT) {
            if (mLoginListener != null) {
                mLoginListener.onLoginFailed(pName, "Você já atingiu o limite de " + LIMIT + " tentativas.");
            }
            return;
        }
        
        try {
            Session s = HibernateUtil.getSessionFactory().getCurrentSession();
            s.beginTransaction();
            List<Login> lista = (List<Login>) s.createQuery("From Login").list();
            if (lista.isEmpty() && mLoginListener != null) {
                mLoginListener.onHasNoLogin();
                return;
            }

            for (Login l : lista) {
                if (pName.equals(l.getNome()) && pPassword.equals(l.getSenha())) {

                    Registrologin rl = new Registrologin();
                    rl.setLogin(l);
                    Date date = new Date();
                    rl.setDataAcesso(date.toString());
                    rl.setUsuario(l.getNome());
                    s.save(rl);
                    s.getTransaction().commit();

                    UserSession.getInstance().beginSession(l);
                    if (mLoginListener != null) {
                        mLoginListener.onLoginSuccess(pName);
                    }
                    return;
                }
            }
            
        } catch (Exception e) {
            MySQL.handleException(e);
            return;
        }
        errors++;
        if (mLoginListener != null) {
            mLoginListener.onLoginFailed(pName, "Usuário ou senha incorreta.");
        }
    }   

    public void setLoginListener(LoginListener pLoginListener) {
        mLoginListener = pLoginListener;
    }   
    
    public interface LoginListener {

        public void onLoginSuccess(String pUserName);

        public void onLoginFailed(String pUserName, String pMessage);
        
        public void onHasNoLogin();
        
    }
    
}